﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Clinica_Frba
{
    public partial class CancelarAtencionMedico : Form
    {
        Conexion sqlCon = Conexion.getInstance();
        Utility util = Utility.getInstance();
        public int idMed = -1;
        int idAgenda;
        DateTime fechaInicio;
        DateTime fechaFin;
        string[] tablaIdDias = { "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };

        public CancelarAtencionMedico()
        {
            InitializeComponent();
        }

        private void CancelarAtencionMedico_Load(object sender, EventArgs e)
        {
            SqlDataReader reader;

            this.Text = "Cancelar Turnos";

            // Parametros grid
            dGridDias.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dGridDias.MultiSelect = true;

            if (idMed == -1)
                buscarMed.Visible = true;
            else
            {
                reader = sqlCon.execQuery("SELECT (Medico_Nombre + ' ' + Medico_Apellido) nom " +
                                      " FROM b_sharp.Medicos where id_medico = " + idMed + ";");
                if (reader.Read())
                {
                    medico.Text = reader.GetString(0);
                    buttonAgenda.Visible = true;
                    buscarMed.Visible = false;
                }
            }
        }

        private void buscarMed_Click(object sender, EventArgs e)
        {
            int med;
            SqlDataReader reader;
            ListaProfesionales medicoForm = new ListaProfesionales();

            med = medicoForm.searchMedico();

            if (med == -1)
                return;

            idMed = med;

            reader = sqlCon.execQuery("SELECT (Medico_Nombre + ' ' + Medico_Apellido) nom " +
                                      " FROM b_sharp.Medicos where id_medico = " + idMed + ";");
            if (reader.Read())
            {
                medico.Text = reader.GetString(0);
                buttonAgenda.Visible = true;
                limpiarDatos();
            }
        }

        private void limpiarDatos()
        {
            agenda.ResetText();

            while (dGridDias.Rows.Count > 0)
                dGridDias.Rows.RemoveAt(0);
        }

        private void buttonAgenda_Click(object sender, EventArgs e)
        {
            SqlDataReader reader;

            BuscarAgenda agendaForm = new BuscarAgenda();

            if (agendaForm.searchAgenda(idMed, out idAgenda))
            {
                reader = sqlCon.execQuery("SELECT fechaInicio, fechaFin " +
                                          " FROM b_sharp.AgendaProfesional ap " +
                                          " WHERE ap.id_agenda = " + idAgenda +
                                          "   AND ap.id_medico = " + idMed + ";");
                if (reader.Read())
                {
                    agenda.Text = reader.GetDateTime(0).Date.ToString("dd/MM/yyyy") + " - " + reader.GetDateTime(1).Date.ToString("dd/MM/yyyy");
                    fechaInicio = reader.GetDateTime(0);
                    fechaFin = reader.GetDateTime(1);

                    loadHorarios();
                }
            }
        }

        private void loadHorarios()
        {
            try
            {
                string qSelect, qFrom, qWhere, query;
                SqlDataAdapter adapter;
                DataTable table = new DataTable();

                qSelect = "SELECT aph.cod_dia, aph.horaInicio, aph.horaFin ";
                qFrom = "FROM b_sharp.AgendaProfHorarios aph ";
                qWhere = "WHERE aph.id_agenda = " + idAgenda + " ";

                query = qSelect + qFrom + qWhere + ";";

                adapter = sqlCon.execQueryGrid(query);
                adapter.Fill(table);

                dGridDias.DataSource = table;

                for (int i = 0; i < dGridDias.Rows.Count; i++)
                {
                    int codDia = Convert.ToInt32(dGridDias[1, i].Value);
                    for (int K = 0; K <= tablaIdDias.Length; K++)
                    {
                        if (codDia == K + 1)
                        {
                            string dia = tablaIdDias[K];
                            dGridDias[0, i].Value = dia;
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error en la consulta");
            }
        }

        private void buttonCancelarAgenda_Click(object sender, EventArgs e)
        {
            SqlCommand cmd;
            string insert;
            string detalle ="";

            if (idAgenda == -1)
            {
                MessageBox.Show("Seleccionar una Agenda", "Error");
                return;
            }

            if (InputBox.Show("Motivo de cancelacion", "Detalle:", ref detalle) != DialogResult.OK)
            {
                MessageBox.Show("Ingrese un motivo de cancelacion", "Error");
                return;
            }
            else if (detalle.Length == 0)
            {
                MessageBox.Show("Ingrese un motivo de cancelacion", "Error");
                return;
            }

            // Cancelar Turnos
            insert =
            "INSERT INTO b_sharp.Cancelaciones (Turno_Numero, Tipo_Cancelacion, Detalle_Cancelacion) " +
            "SELECT Turno_Numero, 2, '" + detalle + "'  FROM b_sharp.Turnos tu " + 
            " WHERE Medico_ID = " + idMed +
            " AND id_agenda = " + idAgenda +
            " AND not exists (SELECT 1 FROM b_sharp.Cancelaciones ca WHERE tu.Turno_Numero = ca.Turno_Numero) " +
            " AND not exists (SELECT 1 FROM b_sharp.Consultas co WHERE tu.Turno_Numero = co.Turno_Num);";

            cmd = new SqlCommand(insert, sqlCon.openCon());
            cmd.ExecuteNonQuery();

            // Cancelar Agenda
            SqlCommand darBaja;
            darBaja = new SqlCommand("UPDATE b_sharp.AgendaProfesional SET bajaLogica = 'S' WHERE id_medico = @idMed AND id_agenda = @idAgenda;", sqlCon.openCon());
            darBaja.Parameters.AddWithValue("@idAgenda", idAgenda);
            darBaja.Parameters.AddWithValue("@idMed", idMed);
            darBaja.ExecuteNonQuery();

            MessageBox.Show("Turnos Cancelados", "Cancelar Agenda");

            limpiarDatos();
        }

        private void buttonCancelarDia_Click(object sender, EventArgs e)
        {
            SqlCommand cmd;
            string insert, delete;
            string detalle = "";
            int idDia;

            if (idAgenda == -1)
            {
                MessageBox.Show("Seleccionar una Agenda", "Error");
                return;
            }

            if (dGridDias.Rows.Count == 0)
            {
                MessageBox.Show("Seleccionar un Dia", "Error");
                return;
            }

            if (InputBox.Show("Motivo de cancelacion", "Detalle:", ref detalle) != DialogResult.OK)
            {
                MessageBox.Show("Ingrese un motivo de cancelacion", "Error");
                return;
            }
            else if (detalle.Length == 0)
            {
                MessageBox.Show("Ingrese un motivo de cancelacion", "Error");
                return;
            }


            foreach (DataGridViewRow row in dGridDias.SelectedRows)
            {
                idDia = (int)row.Cells[1].Value;

                // Cancelar turnos para ese dia
                insert =
                "INSERT INTO b_sharp.Cancelaciones (Turno_Numero, Tipo_Cancelacion, Detalle_Cancelacion) " +
                "SELECT Turno_Numero, 2, '" + detalle + "'  FROM b_sharp.Turnos tu " +
                " WHERE Medico_ID = " + idMed +
                " AND id_agenda = " + idAgenda +
                " AND DATEPART(dw,Turno_Fecha) = " + idDia +
                " AND not exists (SELECT 1 FROM b_sharp.Cancelaciones ca WHERE tu.Turno_Numero = ca.Turno_Numero) " + 
                " AND not exists (SELECT 1 FROM b_sharp.Consultas co WHERE tu.Turno_Numero = co.Turno_Num);";

                cmd = new SqlCommand(insert, sqlCon.openCon());
                cmd.ExecuteNonQuery();

                // Eliminar dia de la agenda
                delete = "DELETE b_sharp.AgendaProfHorarios WHERE id_agenda = @idAgenda AND cod_dia = @codDia";
                cmd = new SqlCommand(delete, sqlCon.openCon());
                cmd.Parameters.AddWithValue("@idAgenda", idAgenda);
                cmd.Parameters.AddWithValue("@codDia", idDia);
                cmd.ExecuteNonQuery();
            }

            MessageBox.Show("Turnos Cancelados", "Cancelar Dia");

            limpiarDatos();
        }
    }
}
